<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Flow Control</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="PHP, learn PHP, language, flow control, if, else, while, foreach, for, language">
<meta name="description" content="In this part of the PHP tutorial, we cover flow control.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Flow control</h1>

<p>
In this part of the PHP tutorial, we will talk about the flow control. 
We will define several keywords
that enable us to control the flow of the PHP script. 
</p>

<div class="center">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* top_horizontal */
google_ad_slot = "3327173442";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<h2>The if statement</h2>

<p>
The <code>if</code> statement has the following general form:
</p>

<pre>
if (expression)
    statement
</pre>

<p>
The <code>if</code> keyword is used to check if an expression is true. If it is true, a
statement is then executed. The statement can be a single statement of a compound statement.
A compound statement consists of multiple statements enclosed by curly brackets.
</p>



<pre class="code">
&lt;?php

$num = 31;

if ($num > 0) 
    echo "\$num variable is positive\n";

?&gt;
</pre>

<p>
We have a $num variable. It is assigned 31. The <code>if</code> keyword checks for a boolean
expression. The expression is put between square brackets. 31 > 0 is true, so the next statement is
executed. 
</p>

<pre>
$ php positive.php 
$num variable is positive
</pre>


<pre class="code">
&lt;?php

$num = 31;

if ($num > 0) {
    echo "\$num variable is positive\n";
    echo "\$num variable equals to $num\n";
}
?&gt;
</pre>

<p>
If we intend to execute more than one statement, we have to put them
inside square brackets. If we did not use them, only the first statement
would be executed. 
</p>

<p>
We can use the <code>else</code> keyword to create a simple branch. 
If the expression inside the square brackets following the if keyword evaluates to 
false, the statement inside the else body is automatically executed. 
</p>

<pre class="code">
&lt;?php

$sex = "female";

if ($sex == "male") {
   echo "It is a boy\n";
} else {
   echo "It is a girl\n";   
}

?&gt;
</pre>

<p>
We have a $sex variable. It has "female" string. The boolean expression evaluates to false 
and we get "It is a girl" in the console.  
</p>

<pre>
$ php boyorgirl.php 
It is a girl
</pre>


<p>
We can create multiple branches using the <code>elseif</code> keyword.
The <code>elseif</code> keyword tests for another condition, if and only if 
the previous condition was not met. Note, that we can use multiple <code>elseif</code>
keywords in our tests.
</p>

<pre class="code">
&lt;?php

$a = 0;

if ($a &lt; 0) {
    echo "\$a is a negative number\n";   
} elseif ($a == 0) {
    echo "\$a is zero\n";   
} else {
    echo "\$a is a positive number\n";   
}

?&gt;
</pre>

<p>
We have a numerical variable and we test it, if it is a negative number or 
positive or if it equals to zero. The first expression evaluates to false. 
The second condition is met. The script
prints '$a is zero' to the console. The rest of the branch is skipped.  
</p>


<h2>The switch statement</h2>

<p>
The <code>switch</code> statement is a selection control flow statement. 
It allows the value of a variable or expression to control the flow of 
program execution via a multiway branch.
It creates multiple branches in a simpler way than using the <code>if</code>, 
<code>elseif</code> statements.
</p>

<p>
The <code>switch</code> statement works with two other keywords. 
The <code>case</code> and the <code>break</code> statements. 
The <code>case</code> keyword is used to test a label against 
a value from the round brackets. If the label equals to the value, the 
statement following the case is executed. The <code>break</code> 
keyword is used to jump out of the <code>switch</code> statement. 
There is an optional <code>default</code> statement. 
If none of the labels equals the value, the default statement is executed. 
</p>

<pre class="code">
&lt;?php

$domain = 'sk';

switch ($domain) {

    case 'us':
        echo "United States\n";
    break;
    case 'de':
        echo "Germany\n";
    break;
    case 'sk':
        echo "Slovakia\n";
    break;
    case 'hu':
        echo "Hungary\n";
    break;
    default:
        echo "Unknown\n";
    break;
}

?&gt;
</pre>

<p>
In our script, we have a <b>$domains</b> variable. It has the 'sk' string.
We use the <code>switch</code> statement to test for the value of
the variable. There are several options. If the value equals to 'us' the
'United States' string is printed to the console. 
</p>

<pre>
$ php domains.php 
Slovakia
</pre>

<p>
We get 'Slovakia'. If we changed the <b>$domains</b> variable to 'rr', we would
get 'Unknown' string. 
</p>


<h2>The while loop</h2>

<p>
The <code>while</code> is a control flow statement that 
allows code to be executed repeatedly
based on a given boolean condition. 
</p>

<p>
This is the general form of the <code>while</code> loop:
</p>

<pre>
while (expression):
    statement
</pre>

<p>
The <code>while</code> loop executes the statement, when the
expression is evaluated to true.
The statement is a simple statement terminated by a semicolon or
a compound statement enclosed in curly brackets. 
</p>

<pre class="code">
&lt;?php

$i = 0;

while ($i &lt; 5) {
    echo "PHP language\n";
    $i++;
}

?&gt;
</pre>

<p>
In the code example, we print "PHP language" string five times to the console. 
</p>

<p>
The <code>while</code>  loop has three parts. Initialization, 
testing and updating. Each execution
of the statement is called a cycle. 
</p>

<pre class="explanation">
 $i = 0;
</pre>

<p>
We initiate the $i variable. It is used as a counter in our script.
</p>

<pre class="explanation">
while ($i &lt; 5) {
   ...
}
</pre>

<p>
The expression inside the square brackets is the second phase, the testing. 
The while loop executes the statements in the body, until the expression is evaluated
to false. 
</p>

<pre class="explanation">
 $i++;
</pre>

<p>
The last, third phase of the <code>while</code> loop. The updating. 
We increment the counter. Note, that
improper handling of the <code>while</code>  loops may lead to endless cycles. 
</p>

<p>
There is another version of the <code>while</code> loop. It is the 
<code>do while</code> loop.
The difference between the two is that this version is guaranteed to run at least once.
</p>

<pre class="code">
&lt;?php

$count = 0;

do {
    echo "$count\n";
} while ($count != 0) 

?&gt;
</pre>

<p>
First the iteration is executed and then the truth expression is evaluated. 
</p>


<p>
The <code>while</code> loop is often used with the 
<code>list()</code> and <code>each()</code>
functions.
</p>

<pre class="code">
&lt;?php

$seasons = array("Spring", "Summer", "Autumn", "Winter");

while (list($idx , $val) = each($seasons)) {
    echo "$val\n";
}

?&gt;
</pre>

<p>
We have four seasons in a <b>$seasons</b> array. We go through all the values 
and print them to the console. The <code>each()</code> function returns 
the current key and value pair from an array and advances the array cursor.
When the function reaches the end of the array, it returns false and the loop is 
terminated. The <code>each()</code> function returns an array. There 
must be an array on the left side of the assignment too. We use the 
<code>list()</code> function to create an array from two variables.
</p>


<h2>The for keyword</h2>

<p>
The <code>for</code> loop does the same thing as the 
<code>while</code> loop. Only it puts all three phases, initialization, 
testing and updating into one place, between the round brackets. It is mainly 
used when the number of iteration is know before entering the loop.
</p>

<p>
Let's have an example with the <code>for</code> loop.
</p>

<pre class="code">
&lt;?php

$days = array("Monday", "Tuesday", "Wednesday", 
              "Thursday", "Friday", 
              "Saturday", "Sunday");

$len = count($days);

for ($i = 0; $i &lt; $len; $i++) {
    echo $days[$i], "\n";
}

?&gt;
</pre>

<p>
We have an array of days of a week. We want to print all these days from this array. We all know that
there are seven days in a week. 
</p>

<pre class="explanation">
 $len = count($days);
</pre>

<p>
Or we can programatically figure out the number of items in an array.
</p>

<pre class="explanation">
 for ($i = 0; $i &lt; $len; $i++) {
    echo $days[$i], "\n"; 
 }
</pre>

<p>
Here we have the <code>for</code> loop construct. The three phases are divided by
semicolons. First, the $i counter is initiated. The initiation part takes place only once.
Next, the test is conducted. If the result of the test is true, the statement is executed. 
Finally, the counter is incremented. This is one cycle. The <code>for</code> loop
iterates until the test expression is false. 
</p>


<h2>The foreach statement</h2>

<p>
The <code>foreach</code> construct simplifies traversing over collections of data. 
It has no explicit counter. The <code>foreach</code> statement goes through the
array one by one and the current value is copied to a variable defined in the construct.
In PHP, we can use it to traverse over an array.
</p>

<pre class="code">
&lt;?php

$planets = array("Mercury", "Venus", "Earth", "Mars", "Jupiter", 
                 "Saturn", "Uranus", "Neptune");

foreach ($planets as $item) {
    echo "$item ";
}

echo "\n";

?&gt;
</pre>

<p>
In this example, we use the <code>foreach</code> statement to go
through an array of planets. 
</p>

<pre class="explanation">
foreach ($planets as $item) {
    echo "$item ";
}
</pre>

<p>
The usage of the <code>foreach</code> statement is straightforward.
The <b>$planets</b> is the array, that we iterate through. The <b>$item</b> is the
temporary variable, that has the current value from the array. The <code>foreach</code> statement 
goes through all the planets and prints them to the console. 
</p>

<pre>
$ php planets.php 
Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune 
</pre>

<p>
Running the above PHP script gives this output.
</p>

<p>
There is another syntax of the <code>foreach</code> statement. It is used with maps.
</p>

<pre class="code">
&lt;?php 

$benelux = array( 
   'be' => 'Belgium',
   'lu' => 'Luxembourg',
   'nl' => 'Netherlands'
);

foreach ($benelux as $key => $value) {
    echo "$key is $value\n";
}

?&gt;
</pre>

<p>
In our script, we have a <b>$benelux</b> map. It contains domain names mapped to 
the benelux states. We traverse the array and print both keys and their values to the console. 
</p>

<pre>
$ php benelux.php 
be is Belgium
lu is Luxembourg
nl is Netherlands
</pre>

<p>
This is the outcome of the script. 
</p>


<h2>The break, continue statements</h2>

<p>
The <code>break</code> statement is used to terminate the loop. 
The <code>continue</code> statement is used to skip a
part of the loop and continue with the next iteration of the loop.
</p>

<pre class="code">
&lt;?php

while (true) {

    $val = rand(1, 30);
    echo $val, " ";
    if ($val == 22) break;

}

echo "\n";

?&gt;
</pre>

<p>
We define an endless <code>while</code> loop. There is only one way to jump out
of a such loop. We must use the <code>break</code> statement. 
We choose a random value from 1 to 30. We print the value. If the
value equals to 22, we finish the endless while loop. 
</p>

<pre>
$ php testbreak.php 
6 11 13 5 5 21 9 1 21 22 
</pre>

<p>
We might get something like this.
</p>

<p>
In the following example, we will print a list of numbers, that cannot be divided by
2 without a remainder. 
</p>

<pre class="code">
&lt;?php

$num = 0;

while ($num &lt; 1000) {

    $num++;
    if (($num % 2) == 0) continue;

    echo "$num ";

}

echo "\n";

?&gt;
</pre>

<p>
We iterate through numbers 1..999 with the <code>while</code> loop.
</p>

<pre class="explanation">
 if (($num % 2) == 0) continue;
</pre>

<p>
If the expression $num % 2 returns 0, the number in question can be divided by 2.
<code>continue</code> statement is executed and the rest of the cycle is skipped.
In our case, the last statement of the loop is skipped and the number is not printed to the
console. The next iteration is started. 
</p>


<p>
In this part of the PHP tutorial, we were talking about control flow structures. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 28, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

